package com.lgl.scsapi.servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 图形滑动验证servlet
 */
@WebServlet(name = "checkImgVerifyServlet", urlPatterns = {"/index/checkImgVerify","/ventIndex/checkImgVerify"})
public class CheckImgVerifyCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String point = request.getParameter("point");
        point = point == null ? "0" : point;
        try {
        	Integer locationX = (Integer) request.getSession().getAttribute("location_x");
            //如果locationX不存在，则说明此session已过期，则重新加载验证图片
        	if (locationX == null){
                outData(response, -4);
            }else if ((Integer.valueOf(point) < locationX + 4) && (Integer.valueOf(point) > locationX - 4)) {
                //说明验证通过，
                outData(response, "success");
            } else {
                outData(response, "error");
            }
		} catch (Exception e) {
			outData(response, "error");
		}
    }
	/**
	 * 输出数据
	 * @param response HttpServletResponse对象
	 * @param data 返回的数据
	 */
    private void outData(HttpServletResponse response, Object data) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            response.setContentType("application/json-rpc;charset=UTF-8");
            out.println(JSON.toJSONString(data));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                out.close();
            }
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    }
}